<template>
	<div class="px-5">
		<div class="mb-4">
			<div class="mb-2">文章标题</div>
			<ypinput v-model="formData.title" placeholder="请输入文章标题" :maxlength="50"></ypinput>
		</div>
		<div class="mb-4">
			<div class="mb-2">文章内容</div>
			<ypeditor v-model="formData.content" />
		</div>
		<div class="mt-4">
			<div class="mb-2">推荐等级</div>
			<div class="flex">
				<ypradio
					v-for="item in recommendList"
					:key="item.id"
					v-model="formData.recommends"
					:value="item.id"
					:title="item.title"
					class="mr-3"
				></ypradio>
			</div>
		</div>
		<div class="flex justify-center py-3 space-x-2">
			<button class="btn btn-hong" type="button" @click="type === 'edit' ? goEdit() : goAdd()">
				<i class="ri-save-line ri-lg pr-1"></i>
				保存
			</button>
			<button class="btn" type="button" @click="router.push('list')">
				<i class="ri-arrow-go-back-line ri-lg pr-1"></i>
				返回
			</button>
		</div>
	</div>
</template>

<script setup>
	import { postData, alter } from '@/common/base'
	import { router } from '@/router'
	import { ref, onMounted } from 'vue'

	const props = defineProps({
		type: { type: String, default: 'add', required: false }, //  add  edit
		id: { type: String, default: '', required: false }
	})

	const formData = ref({
		title: '',
		content: '',
		recommends: null
	})

	const recommendList = ref([])
	const getRecommendData = async () => {
		try {
			const res = await postData('classify/mselect', { pid: 127 })
			if (res.code) {
				const { data } = res
				recommendList.value = data
			}
		} catch (error) {}
	}

	const goAdd = async () => {
		const res = await postData('article/save', formData.value)
		if (res.code) {
			alter({ type: 'alter-success', text: res.msg })
			router.push('list')
		}
	}

	const goEdit = async () => {
		const res = await postData('article/edit', formData.value)
		if (res.code) {
			alter({ type: 'alter-success', text: res.msg })
			router.push('list')
		}
	}

	const getContent = async () => {
		try {
			const res = await postData('article/read', { id: props.id })
			if (res.code) {
				const { id, title, content, recommends } = res.data
				formData.value.id = id
				formData.value.title = title
				formData.value.content = content
				formData.value.recommends = recommends
			}
		} catch (error) {}
	}
	onMounted(() => {
		getRecommendData()
		if (props.type === 'edit') {
			getContent()
		}
	})
</script>
